﻿#include "handle.h"

Handle::Handle(QString num,bool connect_sql)
{
    this->num=num;
    Common::SQL_Lock.lockForRead();
    QString ip       = Common::mysql_data.SQL_ip;
    QString name     = Common::mysql_data.SQL_Sname;
    QString username = Common::mysql_data.Sql_Username;
    QString password = Common::mysql_data.SQL_Password;
    QString cname    = num;
    Common::SQL_Lock.unlock();
    if(connect_sql)
    {
        this->sql.setInformation(ip,name,username,password,cname);
        qDebug()<<"开始连接数据库";
        this->sql.connect();
    }

}
void Handle::handle_localSocket(QString id, QString type, QString data,local_socket *l_socket,Handle *handle,emit_type te_ype)
{
    handle_local(id,type,data,l_socket,handle,te_ype);
    emit this->finish_Task();
}


void Handle::handle_local(QString id, QString type, QString data,local_socket *l_socket,Handle *handle,emit_type te_ype)
{
    //  qDebug()<<type<<QThread::currentThreadId();
    if (te_ype==One&&handle!=this)
    {
        return;
    }
    if(type=="获取服务类型")
    {
        emit this->l_SocketSendData(id,type,"服务器",l_socket,One,"");
    }
    else if(type=="程序类型")
    {
        Common::localSocket_MapLock.lockForWrite();
        if (!Common::localSocket_Map.contains(l_socket))
        {
            qDebug()<<"找不到localsocket!";
        }
        else
        {
            Common::localSocket_Map[l_socket].data()->lock.lockForWrite();
            Common::localSocket_Map[l_socket].data()->Socket_Type=data;
            Common::localSocket_Map[l_socket].data()->Socket_name=id;
            Common::localSocket_Map[l_socket].data()->lock.unlock();
        }
        Common::localSocket_MapLock.unlock();
    }
    else if(type == "read")
    {
        qDebug()<<"read";
        QStringList information=data.split("@@@");
        if (information.size()<2)
        {
            qDebug()<<"解析任务文件出错！";
            qDebug()<<data<<information;
            return;
        }
        QString createid=information[0];
        QString readdata=information[1];
        QStringList readData=readdata.split("&&**");         //解析结果

        QDateTime date=QDateTime::currentDateTime();         //获取当前时间
        QString now_time;
        now_time=date.toString("yyyy-MM-dd-hh:mm:ss");
        QSharedPointer<Caculate_Task> C_task;
        QString tasktype;
        Common::CaculateTask_lock.lockForRead();
        if(!Common::CaculateTask.contains(createid))
        {
            qDebug()<<"找不到CaculateTask!"<<createid;
            return;
        }
        else
        {
            Common::CaculateTask[createid].data()->Data_task_lock.lockForRead();
            tasktype=Common::CaculateTask[createid].data()->Tasktype();
            Common::CaculateTask[createid].data()->set_Taskdecomposition_num(readData.size());
            C_task=Common::CaculateTask[createid];
            Common::CaculateTask[createid].data()->Data_task_lock.unlock();
        }
        Common::CaculateTask_lock.unlock();                                     //获取全局变量

        QStringList taskid;
        QString id;
        qDebug()<<readData.size();
        int  randid[10]={0};
        QString tmp = QString("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
        for(int a=0;a<readData.size();a++)                                       //随机生成ID
        {


            for(int a=0;a<9;a++)
            {
                if(a==0)
                    ++randid[a];
                if(randid[a]==36)
                {
                    randid[a]=0;
                    randid[a+1]++;
                }
            }


            for(int b=9;b>=0;b--)
            {
                id.append(tmp[randid[b]]);
            }
            id=createid+"-"+id;
            taskid.append(id);
            //   qDebug()<<id;
            id.clear();

        }
        qDebug()<<"创建ID完成!";
        C_task.data()->unfinish_task_lock.lockForWrite();
        for(int a=0;a<readData.size();a++)                                      //生成分解任务
        {
            if(a%10000==0)
                qDebug()<<a;
            QSharedPointer<Decomposition_Task> D_task=QSharedPointer<Decomposition_Task>(new Decomposition_Task());
            D_task.data()->init(taskid[a],readData[a]);
            D_task.data()->setBelongTaskID(createid);
            D_task.data()->setCreateTime(now_time);
            D_task.data()->setProblemStatus(task_free);
            D_task.data()->setTaskType(tasktype);
            C_task.data()->Decomposition_unfinish_task[taskid[a]]=D_task;
        }
        C_task.data()->unfinish_task_lock.unlock();
        qDebug()<<"开始存入数据库!";
        sql.create_decomposition_task(taskid,createid,readData,date);
        sql.CaculateTask_createDtaskSuccess(createid,readData.size());
        Assignment_task();                                                        //分配任务
    }
    else if(type=="自动读取未完成任务")
    {
        read_unfinish_task();
    }
    else if(type=="sum")
    {
        QStringList sumresult=data.split("@@@");
        if(sumresult.size()!=2)
        {
            qDebug()<<"接受综合结果时数据错误!";
        }
        QString    C_taskid=sumresult.at(0);
        QString    C_taskresult=sumresult.at(1);
        QString    starttime;
        QString    endtime;
        QString    timeconsuming;
        qDebug()<<"汇总结果结束!任务编号:"<<C_taskid;
        Common::CaculateTask_lock.lockForWrite();
        if(!Common::CaculateTask.contains(C_taskid))
        {
            qDebug()<<"接受综合结果时没有找到相应计算任务编号!计算编号:"<<C_taskid;
            Common::CaculateTask_lock.unlock();
            return;
        }
        Common::CaculateTask[C_taskid].data()->Data_task_lock.lockForRead();
        starttime=Common::CaculateTask[C_taskid].data()->Taskstarttime();
        Common::CaculateTask[C_taskid].data()->Data_task_lock.unlock();
        if(Common::CaculateTask.remove(C_taskid)==0)
        {
            qDebug()<<"删除任务失败!";
        }
        Common::CaculateTask_lock.unlock();
        QDateTime start_time=QDateTime::fromString(starttime,"yyyy-MM-dd-hh:mm:ss");
        QDateTime end_time=QDateTime::currentDateTime();
        endtime=end_time.toString("yyyy-MM-dd-hh:mm:ss");
        int consunmetime=start_time.secsTo(end_time);
        qDebug()<<starttime<<endtime;
        timeconsuming=QString("%1天%2小时%3分钟%4秒").arg(consunmetime/86400).arg(consunmetime%86400/3600).arg(consunmetime%3600/60).arg(consunmetime%60);
        sql.CaculateTask_finish(C_taskid,C_taskresult,endtime,timeconsuming);
        qDebug()<<C_taskid<<"任务完成!耗时:"<<timeconsuming;
    }
    else if(type=="初始化完成")
    {
        LocalSockt_unfinshsenddata(l_socket);
    }
    else if(type=="自动读取DLL信息")
    {
        ReadDll();
    }
    else if(type=="定时清理SQL")
    {
        //  qDebug()<<"定时清理进入"<<QThread::currentThreadId();
        sql.CleanTask();
        //  qDebug()<<"定时清理完毕"<<QThread::currentThreadId();
    }
    else if(type=="SQL心跳连接")
    {
        sql.KeepSqlConnect();
    }
    else
    {
        qDebug()<<type;
    }
    //qDebug()<<"out"<<QThread::currentThreadId();
}
void Handle::handle_tcpSocket(QString id, QString type, QString data,tcp_socket *t_socket,Handle *handle,emit_type te_ype)
{
    handle_tcp(id,type,data,t_socket,handle,te_ype);
    emit this->finish_Task();
}


void Handle::handle_tcp(QString id, QString type, QString data,tcp_socket *t_socket,Handle *handle,emit_type te_ype)
{

    if (te_ype==One&&handle!=this)
    {
        return;
    }

    if(this->num=="handle_sql"&&type=="计算结果")
    {
        qDebug()<<"丰富的省份";
    }

    if(type!="计算结果" && type!="心跳包")
        qDebug()<<id<<type;

    //  qDebug()<<type<<QThread::currentThreadId();
    if(type=="传输DLL")
    {
        QStringList  data1=data.split("&&@@");
        if(data1.size()<2)
        {
            qDebug()<<"传输DLL出错!";
            return;
        }
        QString dll_Name=data1[0];
        QString dll_Data=data1[1];
        QString dllmd5=GetMD5(QByteArray::fromBase64(dll_Data.toLatin1()));
        QString file_path=QCoreApplication::applicationDirPath()+"\\"+"DLL"+"\\"+dll_Name;
        isDirExist(QCoreApplication::applicationDirPath()+"\\"+"DLL");                //是否存在DLL文件夹,没有则创建
        if(isFileExist(file_path))
        {
            qDebug()<<"存在同名DLL!!";
            QFile file(file_path);
            if(!file.open(QIODevice::ReadOnly))
            {
                return;
            }
            QByteArray dllData= file.readAll();
            file.close();
            QString thismd5=GetMD5(dllData);
            //当MD5相同则不替换
            if(thismd5==dllmd5)
            {
                emit this->t_SocketSendData(id,"DLL效验",dll_Name+"$$"+dllmd5,t_socket,All,"计算节点");
            }
            else
            {
                QFile  file(file_path);
                if (file.open(QFile::WriteOnly|QFile::Truncate))
                {
                    QByteArray data1=QByteArray::fromBase64(dll_Data.toLatin1());
                    file.write(data1);
                    file.close();
                }
                else
                {
                    qDebug()<<"写入DLL失败!!";
                    emit this->t_SocketSendData(id,type,"写入Dll失败",t_socket,One,"");
                    return ;
                }
            }
            return ;
        }
        QFile  file(file_path);
        if (file.open(QIODevice::Append))
        {
            QByteArray data1=QByteArray::fromBase64(dll_Data.toLatin1());
            file.write(data1);
            file.close();
        }
        else
        {
            qDebug()<<"写入DLL失败!!";
            emit this->t_SocketSendData(id,type,"写入Dll失败",t_socket,One,"");
            return ;
        }
        qDebug()<<"接受DLL成功！DLL名称:"<<dll_Name;
        emit this->t_SocketSendData(id,"DLL效验",dll_Name+"$$"+dllmd5,t_socket,All,"计算节点");
    }
    else if(type == "传输任务文件")
    {
        qDebug()<<"传输任务文件"<<data.size();
        QStringList  data1=data.split("&&&!@@@");
        if(data1.size()<2)
        {
            qDebug()<<"传输任务文件出错!";
            return;
        }
        QString Task_Name=data1[0];
        QString Task_Data=data1[1];
        QString createid;
        /////
        /////  记录内容文件并保存到数据库中
        ///
        qDebug()<<Task_Name<<Task_Data.size();
        Common::tcp_server_SocketMapLock.lockForRead();
        if (!Common::tcp_server_SocketMap.contains(t_socket))
        {
            qDebug()<<"无法找到tcpsocket!";
        }
        else
        {
            Common::tcp_server_SocketMap[t_socket].data()->lock.lockForWrite();
            createid=Common::tcp_server_SocketMap[t_socket].data()->Socket_name;
            Common::tcp_server_SocketMap[t_socket].data()->lock.unlock();
        }
        Common::tcp_server_SocketMapLock.unlock();
        QString CaculateTaskID=sql.create_caculate_task(Task_Name,Task_Data,createid);
        if(CaculateTaskID.isEmpty())
        {
            qDebug()<<"创建计算任务失败!";
            return;
        }
        QSharedPointer<Caculate_Task> c_task=QSharedPointer<Caculate_Task>(new Caculate_Task(CaculateTaskID,Task_Name,Task_Data));
        c_task.data()->set_TaskIsFinish("N");
        c_task.data()->set_TaskstartTime(QDateTime::currentDateTime().toString("yyyy-MM-dd-hh:mm:ss"));
        c_task.data()->set_TaskLastupdate_time(QDateTime::currentDateTime());
        Common::CaculateTask_lock.lockForWrite();
        Common::CaculateTask[CaculateTaskID]=c_task;
        Common::CaculateTask_lock.unlock();
        QSharedPointer<M_Socket> l_socket=Common::GetLocal_Socket();
        QString send_data=Task_Name+"***"+CaculateTaskID+"***"+Task_Data;
        if(l_socket.isNull())
        {
            LocalSocket_SetUnfinshsenddata("服务器","read",send_data,One,"");        //将发送信息储存起来，等本地计算模块连接时发送
            qDebug()<<"获取本地loaclsocket失败!";
            return;
        }
        emit l_SocketSendData(id,"read",send_data,l_socket->l_socket,One,"");
    }
    else if(type == "程序类型")
    {
        //  qDebug()<<data;
        Common::tcp_server_SocketMapLock.lockForWrite();
        if(!Common::tcp_server_SocketMap.contains(t_socket))
        {
            qDebug()<<"找不到tcpsocket";
        }
        else
        {
            Common::tcp_server_SocketMap[t_socket].data()->lock.lockForWrite();
            Common::tcp_server_SocketMap[t_socket].data()->Socket_name=id;
            Common::tcp_server_SocketMap[t_socket].data()->Socket_Type=data;
            Common::tcp_server_SocketMap[t_socket].data()->lock.unlock();
        }
        Common::tcp_server_SocketMapLock.unlock();
    }
    else if(type == "计算模块状态")
    {
        QStringList  result=data.split("***");
        if (result.size()!=2)
        {
            qDebug()<<"计算模块状态接受错误!";
            return;
        }
        QStringList computerdata=result.at(0).split("&&&");
        QStringList Caculate_status=result.at(1).split("&&&");
        QList<CaculateNode_status> status;
        for(int a=0;a<Caculate_status.size();a++)
        {
            if(Caculate_status[a]=="空闲")
            {
                status.append(Cfree);
            }
            else if(Caculate_status[a]=="忙碌")
            {
                status.append(Caculating);
            }else{
                qDebug()<<"未知节点状态!!!";
            }
        }
        Common::tcp_server_SocketMapLock.lockForRead();
        Common::tcp_server_SocketMap[t_socket].data()->lock.lockForWrite();
        Common::tcp_server_SocketMap[t_socket].data()->cpu_cout=computerdata[1];
        Common::tcp_server_SocketMap[t_socket].data()->Memory_size=computerdata[7];
        Common::tcp_server_SocketMap[t_socket].data()->Memory_usage=computerdata[6];
        Common::tcp_server_SocketMap[t_socket].data()->Residual_memory=computerdata[8];
        if(Common::tcp_server_SocketMap[t_socket].data()->Caculate_status.isEmpty())
        {
            Common::tcp_server_SocketMap[t_socket].data()->Caculate_status=status;
        }
        Common::tcp_server_SocketMap[t_socket].data()->lock.unlock();
        //     qDebug()<< Common::tcp_server_SocketMap.size();
        Common::tcp_server_SocketMapLock.unlock();
        //     qDebug()<<result;
        //  qDebug()<<"计算模块状态";
        Assignment_task();
    }
    else if(type=="计算结果")
    {

        //  qDebug()<<"计算结果进入"<<QThread::currentThreadId();

        QStringList result=data.split("@@@");
        if(result.size()<3)
        {
            qDebug()<<"计算结果出错!";
            return;
        }
        QString taskid=result.at(0);
        QString taskbelongid=result.at(1);
        QString taskresult=result.at(2);
        // qDebug()<<"完成任务"<<taskid;
        bool    Caculate_empty=false;
        bool    Unfinsh_empty=false;
        QString starttime;
        QDateTime date=QDateTime::currentDateTime();
        QString now_time=date.toString("yyyy-MM-dd-hh:mm:ss");

        Common::tcp_server_SocketMapLock.lockForRead();
        if(!Common::tcp_server_SocketMap.contains(t_socket))
        {
            qDebug()<<"找不到对应t_socket!";
            Common::tcp_server_SocketMapLock.unlock();
            return;
        }
        Common::tcp_server_SocketMap[t_socket].data()->lock.lockForWrite();
        if(!Common::tcp_server_SocketMap[t_socket].data()->task_id.removeOne(taskid))
        {
            qDebug()<<"未在计算节点中发现对应计算任务!任务ID:"<<taskid;
            Common::tcp_server_SocketMap[t_socket].data()->lock.unlock();
            Common::tcp_server_SocketMapLock.unlock();
            return;
        }
        // qDebug()<<"改变节点状态"<<QThread::currentThreadId();
        if(Common::tcp_server_SocketMap[t_socket].data()->Caculate_status.size()>Common::tcp_server_SocketMap[t_socket].data()->task_id.size())
        {
            int num= Common::tcp_server_SocketMap[t_socket].data()->Caculate_status.indexOf(Caculating);                                        //修改计算节点信息，移除计算任务id，更新计算节点状态
            if(num!=-1)
            {
                Common::tcp_server_SocketMap[t_socket].data()->Caculate_status.replace(num,Cfree);
            }
        }
        Common::tcp_server_SocketMap[t_socket].data()->lock.unlock();
        Common::tcp_server_SocketMapLock.unlock();
        //   qDebug()<<"分配任务"<<QThread::currentThreadId();
        Assignment_task();
        //    qDebug()<<"分配完毕"<<QThread::currentThreadId();
        Common::CaculateTask_lock.lockForRead();

        if(!Common::CaculateTask.contains(taskbelongid))             //未找到计算任务
        {
            qDebug()<<"未找到计算任务任务ID"<<taskbelongid;

            Common::CaculateTask_lock.unlock();
            return;
        }

        //   qDebug()<<"finish"<<Common::CaculateTask.size()<<QThread::currentThreadId();
        Common::CaculateTask[taskbelongid].data()->Caculating_task_lock.lockForWrite();
        if(!Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task.contains(taskid)) //未找到分解任务
        {
            qDebug()<<"未找到分解任务!分解任务ID:"<<taskid;
            Common::Common::CaculateTask[taskbelongid].data()->Caculating_task_lock.unlock();
            Common::CaculateTask_lock.unlock();
            return;
        }
        // qDebug()<<"修改Caculate队列"<<QThread::currentThreadId();
        Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task[taskid].data()->DTask_Lock.lockForWrite();             //修改Caculate队列中的信息并移除
        starttime=Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task[taskid].data()->getStartTime();
        Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task[taskid].data()->setProblemStatus(task_finish);
        Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task[taskid].data()->setTaskResult(taskresult);
        Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task[taskid].data()->setFinishTime(now_time);
        QSharedPointer<Decomposition_Task> D_task=Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task[taskid];
        Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task[taskid].data()->DTask_Lock.unlock();
        // qDebug()<<"修改Caculate队列完毕"<<QThread::currentThreadId();
        Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task.remove(taskid);

        if(Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task.empty())
        {
            Caculate_empty=true;
        }
        Common::CaculateTask[taskbelongid].data()->Caculating_task_lock.unlock();



        Common::CaculateTask[taskbelongid].data()->finish_task_lock.lockForWrite();                                                      //在finish中加入
        Common::CaculateTask[taskbelongid].data()->Decomposition_finish_task[taskid]=D_task;
        Common::CaculateTask[taskbelongid].data()->finish_task_lock.unlock();






        Common::CaculateTask[taskbelongid].data()->unfinish_task_lock.lockForRead();
        if(Common::CaculateTask[taskbelongid].data()->Decomposition_unfinish_task.isEmpty())
        {
            Unfinsh_empty=true;

        }
        Common::CaculateTask[taskbelongid].data()->unfinish_task_lock.unlock();


        Common::CaculateTask[taskbelongid].data()->Data_task_lock.lockForRead();
        QDateTime lastupdatetime=Common::CaculateTask[taskbelongid].data()->TaskLastupdate_time();
        // QString   task_schedule=Common::CaculateTask[taskbelongid].data()->Taskschedule();
        int       task_num=Common::CaculateTask[taskbelongid].data()->Taskdecomposition_num();
        Common::CaculateTask[taskbelongid].data()->Data_task_lock.unlock();

        int finishtasksize;
        bool updateCaculateschedule=false;
        QDateTime nowtime=QDateTime::currentDateTime();
        if(lastupdatetime.msecsTo(nowtime)>5000)
        {
            updateCaculateschedule=true;
            Common::CaculateTask[taskbelongid].data()->finish_task_lock.lockForRead();

            finishtasksize=Common::CaculateTask[taskbelongid].data()->Decomposition_finish_task.size();

            Common::CaculateTask[taskbelongid].data()->finish_task_lock.unlock();

            Common::CaculateTask[taskbelongid].data()->Data_task_lock.lockForWrite();
            Common::CaculateTask[taskbelongid].data()->set_Taskschedule(QString::number((double)finishtasksize/(double)task_num*100));
            qDebug()<<QString::number((double)finishtasksize/(double)task_num*100)<<QString::number((double)finishtasksize)<<(double)task_num;
            Common::CaculateTask[taskbelongid].data()->set_TaskLastupdate_time(QDateTime::currentDateTime());

            Common::CaculateTask[taskbelongid].data()->Data_task_lock.unlock();

        }
        Common::CaculateTask_lock.unlock();

        if(updateCaculateschedule)
        {
            sql.CaculateTask_updateschedule(taskbelongid,(double)finishtasksize/(double)task_num*100);
        }
        sql.Decomposition_taskfinish(taskbelongid,taskid,taskresult,starttime,now_time);

        if(Unfinsh_empty&&Caculate_empty)    //如果未计算任务队列、计算中队列都计算完毕，则开始统计结果
        {
            qDebug()<<"开始完成任务";
            FindFinsh_Task();
        }

    }
    else if(type=="DLL效验")
    {
        ReadDll();
        QStringList md5data=GetDLLMd5();
        this->t_SocketSendData("服务器","DLL效验",md5data.join("@@"),t_socket,One,"");
    }
    else if(type=="缺失DLL")
    {
        QStringList LackDllname=data.split("@@");
        for(int a=0;a<LackDllname.size();a++)
        {
            QString file_path=QCoreApplication::applicationDirPath()+"\\"+"DLL"+"\\"+LackDllname[a];
            QFile file(file_path);
            if(!file.open(QIODevice::ReadOnly))
            {
                qDebug()<<"打开"<<LackDllname[a]<<"失败!";
                continue;
            }
            QByteArray dllData= file.readAll();
            file.close();
            QString senddata=LackDllname[a]+"&&@@"+dllData.toBase64();
            emit this->t_SocketSendData(id,"传输DLL",senddata,t_socket,One,"");
            qDebug()<<LackDllname[a];
        }
        ReadDll();
        QStringList md5data=GetDLLMd5();
        this->t_SocketSendData("服务器","DLL效验",md5data.join("@@"),t_socket,One,"");
    }else if(type=="心跳包")
    {
        emit this->t_SocketSendData("服务器","心跳包","",t_socket,One,"");
    }
    else if(type=="管理端获取节点信息")
    {
        emit this->t_SocketSendData("服务器","管理端获取节点信息",CaculateNode_information(),t_socket,One,"");
    }
    else if(type=="查询任务")
    {

        QList<QStringList> result=sql.GetCaculate_Task(data);
        QStringList         data1;
        QString             senddata;
        for(int a=0;a<result.size();a++)
        {
            if(result[a][6].size()>100)
            {
                result[a][6]=result[a][6].mid(0,100);
                result[a][6].append("......");
            }
            data1.append(result[a].join(",#"));
        }
        senddata=data1.join("#!");
        emit this->t_SocketSendData("服务器","查询任务",senddata,t_socket,One,"");
    }
    else if(type=="删除任务")
    {
        Common::CaculateTask_lock.lockForWrite();
        if(Common::CaculateTask.contains(data))
        {
            if(Common::CaculateTask.remove(data)==0)
            {
                qDebug()<<"删除任务失败!";
            }
        }

        Common::CaculateTask_lock.unlock();

        qDebug()<<"开始删除!";
        QDateTime deletetime=QDateTime::currentDateTime();
        bool result=sql.DeleteCaculate_Task(data);
        if (result)
        {
            QString senddata=QString("删除成功!耗时:%1秒").arg(deletetime.secsTo(QDateTime::currentDateTime()));
            qDebug()<<senddata;
            emit this->t_SocketSendData("服务器",type,senddata,t_socket,One,"");
        }
        else
        {
            QString senddata=QString("删除失败!耗时:%1秒").arg(deletetime.secsTo(QDateTime::currentDateTime()));
            qDebug()<<senddata;
            emit this->t_SocketSendData("服务器",type,senddata,t_socket,One,"");
        }
    }
    else if(type=="任务失败")
    {
        QStringList result=data.split("@@@");
        if(result.size()<2)
        {
            qDebug()<<"计算结果出错!";
            return;
        }
        qDebug()<<result;
        QString taskid=result.at(0);
        QString taskbelongid=result.at(1);
        qDebug()<<"任务计算失败!任务ID:"<<taskid;
        Common::tcp_server_SocketMapLock.lockForRead();
        if(!Common::tcp_server_SocketMap.contains(t_socket))
        {
            qDebug()<<"找不到对应t_socket!任务ID:"<<taskid;
            Common::tcp_server_SocketMapLock.unlock();
            return;
        }
        Common::tcp_server_SocketMap[t_socket].data()->lock.lockForWrite();
        if(!Common::tcp_server_SocketMap[t_socket].data()->task_id.removeOne(taskid))
        {
            qDebug()<<"未在计算节点中发现对应计算任务!任务ID:"<<taskid;
            return;
        }
        int num= Common::tcp_server_SocketMap[t_socket].data()->Caculate_status.indexOf(Caculating);                                        //修改计算节点信息，移除计算任务id，更新计算节点状态
        if(num!=-1)
        {
            Common::tcp_server_SocketMap[t_socket].data()->Caculate_status.replace(num,Cfree);
        }
        Common::tcp_server_SocketMap[t_socket].data()->lock.unlock();
        Common::tcp_server_SocketMapLock.unlock();
        Common::CaculateTask_lock.lockForRead();

        if(!Common::CaculateTask.contains(taskbelongid))             //未找到计算任务
        {
            qDebug()<<"未找到计算任务!任务ID"<<taskbelongid;

            Common::CaculateTask_lock.unlock();
            return;
        }

        //   qDebug()<<"finish"<<Common::CaculateTask.size()<<QThread::currentThreadId();
        Common::CaculateTask[taskbelongid].data()->Caculating_task_lock.lockForWrite();
        if(!Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task.contains(taskid)) //未找到分解任务
        {
            qDebug()<<"未找到分解任务!任务ID:"<<taskid;
            Common::Common::CaculateTask[taskbelongid].data()->Caculating_task_lock.unlock();
            Common::CaculateTask_lock.unlock();
            return;
        }
        qDebug()<<"here";
        Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task[taskid].data()->DTask_Lock.lockForWrite();             //修改Caculate队列中的信息并移除

        Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task[taskid].data()->setProblemStatus(task_free);

        QSharedPointer<Decomposition_Task> D_task=Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task[taskid];
        Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task[taskid].data()->DTask_Lock.unlock();
        Common::CaculateTask[taskbelongid].data()->Decomposition_Caculating_task.remove(taskid);


        Common::CaculateTask[taskbelongid].data()->Caculating_task_lock.unlock();



        Common::CaculateTask[taskbelongid].data()->unfinish_task_lock.lockForWrite();
        Common::CaculateTask[taskbelongid].data()->Decomposition_unfinish_task[taskid]=D_task;
        Common::CaculateTask[taskbelongid].data()->unfinish_task_lock.unlock();

        Common::CaculateTask_lock.unlock();
        qDebug()<<"失败任务处理成功!";
        Assignment_task();
        ReadDll();
        QStringList md5data=GetDLLMd5();
        this->t_SocketSendData("服务器","DLL效验",md5data.join("@@"),t_socket,One,"");

    }
    else if(type=="DLL完整")
    {
        Common::tcp_server_SocketMapLock.lockForRead();
        Common::tcp_server_SocketMap[t_socket].data()->lock.lockForWrite();
        Common::tcp_server_SocketMap[t_socket].data()->Is_DllComplete=true;
        Common::tcp_server_SocketMap[t_socket].data()->lock.unlock();
        Common::tcp_server_SocketMapLock.unlock();
        Assignment_task();
    }
    //qDebug()<<"out"<<QThread::currentThreadId();
}


bool Handle::isFileExist(QString fullFileName)
{

    QFileInfo fileInfo(fullFileName);
    if(fileInfo.isFile())
    {
        return true;
    }
    return false;
}


bool Handle::isDirExist(QString fullPath)
{
    QDir dir(fullPath);
    if(dir.exists())
    {
        return true;
    }
    else
    {
        bool ok = dir.mkdir(fullPath);//只创建一级子目录，即必须保证上级目录存在
        return false;
    }
}




QString Handle::rand_id(int length)
{
    QString tmp = QString("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    QString str = QString();
    QTime t;
    t= QTime::currentTime();
    qsrand(t.msec()+t.second()*1000);
    str.clear();
    for(int i=0;i<length;i++)
    {
        int ir = qrand()%tmp.length();
        str.append(tmp.at(ir));
    }
    return str;
}


void Handle::Assignment_task()                 //分配任务
{
    //  qDebug()<<"enter"<<QThread::currentThreadId();
    //  struct timeval tpstart,tpend;
    //  float timeuse;
    //  gettimeofday(&tpstart,NULL);
    // qDebug()<<"获取空闲计算节点"<<QThread::currentThreadId();
    QSharedPointer<M_Socket> socket=Common::GetFree_Caculatenode();   //分配时已经改变socket修改socket一个计算线程为计算，因此不用考虑多线程是否冲突

    if (socket.isNull())
    {
        //   qDebug()<<"没有空闲计算节点！";

        return;
    }


    QSharedPointer<Decomposition_Task> D_task=Common::GetFree_Decomposition_Task();

    if(D_task.isNull())
    {
        //  qDebug()<<"没有任务,重置计算节点信息";
        socket.data()->lock.lockForWrite();
        if(socket.data()->task_id.size()<socket.data()->Caculate_status.size())
        {
            int num= socket.data()->Caculate_status.indexOf(Caculating);
            socket.data()->Caculate_status[num]=Cfree;
        }
        socket.data()->lock.unlock();
        return;
    }
    //   qDebug()<<"获取空闲计算任务完毕"<<QThread::currentThreadId();
    D_task.data()->DTask_Lock.lockForRead();     //获取任务id
    QString taskid=D_task.data()->getTaskid();
    QString taskdata=D_task.data()->getTaskData();
    QString tasktype=D_task.data()->getTaskType();
    QString belongCtaskid=D_task.data()->getBelongTaskID();
    D_task.data()->DTask_Lock.unlock();

    socket.data()->lock.lockForWrite();         //获取computer_id
    socket.data()->task_id.append(taskid);
    QString computer_id=socket.data()->Socket_name;
    socket.data()->lock.unlock();
    D_task.data()->DTask_Lock.lockForWrite();   //设置BelongComputer
    D_task.data()->setBelongComputer(computer_id);
    QDateTime date=QDateTime::currentDateTime();
    QString now_time=date.toString("yyyy-MM-dd-hh:mm:ss");
    D_task.data()->setStartTime(now_time);
    D_task.data()->DTask_Lock.unlock();
    QStringList task_data;
    task_data.append(taskid);
    task_data.append(tasktype);
    task_data.append(belongCtaskid);
    task_data.append(taskdata);
    QString senddata=task_data.join("**&&##");
    //   gettimeofday(&tpend,NULL);
    //    timeuse=(1000000*(tpend.tv_sec-tpstart.tv_sec) + tpend.tv_usec-tpstart.tv_usec);
    // qDebug()<<"分配任务花费"<<timeuse<<"us"<<QThread::currentThreadId();
    //  qDebug()<<"发送任务!";
    emit this->t_SocketSendData("服务器","计算任务",senddata,socket->t_socket,One,"");

    Assignment_task();
}


void Handle::read_unfinish_task()
{
    QList<QStringList> unfinish_Ctask;
    qDebug()<<"开始读取数据库中未完成任务";
    Common::CaculateTask_lock.lockForRead();
    if (!Common::CaculateTask.isEmpty())       //如果任务队列不为空，则不需要读取
    {
        Common::CaculateTask_lock.unlock();
        return;
    }
    Common::CaculateTask_lock.unlock();
    unfinish_Ctask=sql.Get_unfinshCaculateTask();
    for(int a=0;a<unfinish_Ctask.size();a++)
    {
        QStringList data=unfinish_Ctask[a];
        Common::CaculateTask_lock.lockForRead();
        if(Common::CaculateTask.contains(data.first()))
        {
            Common::CaculateTask_lock.unlock();
            continue;
        }
        Common::CaculateTask_lock.unlock();
        QSharedPointer<Caculate_Task> Ctask=QSharedPointer<Caculate_Task>(new Caculate_Task(data.first(),data.at(1),data.at(6)));  //建立Caculate_Task
        Ctask.data()->set_TaskcreateId(data.at(3));
        Ctask.data()->set_TaskIsFinish(data.at(8));
        Ctask.data()->set_Taskschedule(data.at(2));
        Ctask.data()->set_TaskstartTime(data.at(4));
        Ctask.data()->set_Taskdecomposition_num(data.at(11).toInt());
        Ctask.data()->set_TaskLastupdate_time(QDateTime::currentDateTime());
        if(data.at(10)=="N")
        {
            QSharedPointer<M_Socket> l_socket=Common::GetLocal_Socket();
            QString send_data=data.at(1)+"***"+data.at(0)+"***"+data.at(6);
            if(l_socket.isNull())
            {
                Common::CaculateTask_lock.lockForWrite();
                if(!Common::CaculateTask.contains(data.first()))
                {
                    //   qDebug()<<Ctask.data()->Decomposition_unfinish_task.size()<<Ctask.data()->Decomposition_finish_task.size();
                    Common::CaculateTask[Ctask.data()->Taskid()]=Ctask;
                }
                Common::CaculateTask_lock.unlock();
                // qDebug()<<send_data;
                qDebug()<<"获取本地loaclsocket失败!";
                LocalSocket_SetUnfinshsenddata("服务器","read",send_data,One,"");
                return;
            }
            emit l_SocketSendData("服务器","read",send_data,l_socket->l_socket,One,"");
        }
        QList<QStringList>  decomposition_task;
        decomposition_task=sql.Get_DecompositionTask(data.at(0));
        for(int b=0;b<decomposition_task.size();b++)
        {
            QStringList Ddata=decomposition_task.at(b);
            QSharedPointer<Decomposition_Task> Dtask=QSharedPointer<Decomposition_Task>(new Decomposition_Task());  //建立DecompositionTask
            Dtask.data()->init(Ddata.at(0),Ddata.at(2));
            Dtask.data()->setBelongTaskID(Ddata.at(1));
            Dtask.data()->setCreateTime(Ddata.at(4));
            Dtask.data()->setFinishTime(Ddata.at(6));
            Dtask.data()->setStartTime(Ddata.at(5));
            Dtask.data()->setTaskResult(Ddata.at(3));
            Dtask.data()->setTaskType(data.at(1));
            Dtask.data()->setProblemStatus(task_statu(Ddata.at(7)));
            if(Dtask.data()->getProblemStatus()==task_free)
            {
                Ctask.data()->Decomposition_unfinish_task[Dtask.data()->getTaskid()]=Dtask;
            }
            else if(Dtask.data()->getProblemStatus()==task_finish)
            {
                Ctask.data()->Decomposition_finish_task[Dtask.data()->getTaskid()]=Dtask;
            }
            else
            {
                qDebug()<<"未知的任务状态!";
            }
        }
        Common::CaculateTask_lock.lockForWrite();
        if(!Common::CaculateTask.contains(data.first()))
        {
            qDebug()<<Ctask.data()->Decomposition_unfinish_task.size()<<Ctask.data()->Decomposition_finish_task.size();
            Common::CaculateTask[Ctask.data()->Taskid()]=Ctask;
        }
        Common::CaculateTask_lock.unlock();
    }
    if(unfinish_Ctask.isEmpty())
    {
        qDebug()<<"没有空闲任务!";
    }
    else
    {
        qDebug()<<"数据库读取完毕!";
        qDebug()<<"空闲计算节点分配任务!";
        Assignment_task();
    }
}


void Handle::SumResult(QString C_Taskid)
{
    QString C_Tasktype;
    Common::CaculateTask_lock.lockForWrite();
    qDebug()<<"开始查找是否有此任务!";
    if(!Common::CaculateTask.contains(C_Taskid))
    {
        qDebug()<<"综合结果时找不到对应计算任务！";
        Common::CaculateTask_lock.unlock();
        return;
    }

    Common::CaculateTask[C_Taskid].data()->Caculating_task_lock.lockForRead();              //加锁判断计算队列为空
    qDebug()<<"判断计算队列是否为空!";
    if(!Common::CaculateTask[C_Taskid].data()->Decomposition_Caculating_task.isEmpty())
    {
        qDebug()<<"综合结果时发现计算任务未完成!";
        Common::CaculateTask[C_Taskid].data()->Caculating_task_lock.unlock();
        Common::CaculateTask_lock.unlock();
        return;
    }
    Common::CaculateTask[C_Taskid].data()->Caculating_task_lock.unlock();

    Common::CaculateTask[C_Taskid].data()->unfinish_task_lock.lockForRead();               //加锁判断未完成队列为空
    qDebug()<<"判断未计算队列是否为空";
    if(!Common::CaculateTask[C_Taskid].data()->Decomposition_unfinish_task.isEmpty())
    {
        qDebug()<<"综合结果时发现计算任务未完成!";
        Common::CaculateTask[C_Taskid].data()->unfinish_task_lock.unlock();
        Common::CaculateTask_lock.unlock();
        return;
    }
    Common::CaculateTask[C_Taskid].data()->unfinish_task_lock.unlock();

    QStringList All_result;

    Common::CaculateTask[C_Taskid].data()->Data_task_lock.lockForWrite();
    C_Tasktype=Common::CaculateTask[C_Taskid].data()->Tasktype();
    Common::CaculateTask[C_Taskid].data()->set_TaskIsFinish("Y");
    Common::CaculateTask[C_Taskid].data()->Data_task_lock.unlock();
    QDateTime start=QDateTime::currentDateTime();
    qDebug()<<"计算结果开始封装,准备汇总结果";
    Common::CaculateTask[C_Taskid].data()->finish_task_lock.lockForRead();
    QMap<QString,QSharedPointer<Decomposition_Task>>::const_iterator i;
    for (i = Common::CaculateTask[C_Taskid].data()->Decomposition_finish_task.constBegin(); i != Common::CaculateTask[C_Taskid].data()->Decomposition_finish_task.constEnd(); ++i)
    {
        i.value().data()->DTask_Lock.lockForRead();
        All_result.append(i.value().data()->getTaskResult());
        i.value().data()->DTask_Lock.unlock();
    }
    Common::CaculateTask[C_Taskid].data()->finish_task_lock.unlock();

    Common::CaculateTask_lock.unlock();
    qDebug()<<"结果封装完毕!耗时:"<<start.secsTo(QDateTime::currentDateTime())<<"秒";

    // qDebug()<<All_result;
    QSharedPointer<M_Socket> l_socket=Common::GetLocal_Socket();
    QString send_data=C_Taskid+"***"+C_Tasktype+"***"+All_result.join("!!!");
    if(l_socket.isNull())
    {
        qDebug()<<"获取本地loaclsocket失败!";
        LocalSocket_SetUnfinshsenddata("服务器","sum",send_data,One,"");
        return;
    }
    qDebug()<<"开始汇总!";
    emit l_SocketSendData("服务器","sum",send_data,l_socket->l_socket,One,"");
}


void Handle::FindFinsh_Task()
{
    QStringList Finish_Taskid;
    Common::CaculateTask_lock.lockForRead();
    QMap<QString,QSharedPointer<Caculate_Task>>::const_iterator i;
    qDebug()<<"开始查找是否有完成任务!";
    for (i = Common::CaculateTask.constBegin(); i != Common::CaculateTask.constEnd(); ++i)
    {
        bool Unfinishtask=false;
        bool Caculatetask=false;
        i.value().data()->unfinish_task_lock.lockForRead();             //加锁判断未完成任务队列是否为空
        if(i.value().data()->Decomposition_unfinish_task.isEmpty())
        {
            Unfinishtask=true;
        }
        i.value().data()->unfinish_task_lock.unlock();

        i.value().data()->Caculating_task_lock.lockForRead();          //加锁判断计算队列是否为空
        if(i.value().data()->Decomposition_Caculating_task.isEmpty())
        {
            Caculatetask=true;
        }
        i.value().data()->Caculating_task_lock.unlock();

        if(Unfinishtask&&Caculatetask)                                //如果
        {
            i.value().data()->Data_task_lock.lockForRead();
            Finish_Taskid.append(i.value().data()->Taskid());
            i.value().data()->Data_task_lock.unlock();
        }
    }
    Common::CaculateTask_lock.unlock();

    for(int a=0;a<Finish_Taskid.size();a++)
    {
        SumResult(Finish_Taskid.at(a));
    }
}


void Handle::LocalSockt_unfinshsenddata(local_socket *l_socket)
{
    Common::Localsocket_unsenddataLock.lockForWrite();
    for(int a=0;a<Common::Localsocket_unsenddata.size();a++)
    {
        l_socket->send_message(Common::Localsocket_unsenddata[a].id,Common::Localsocket_unsenddata[a].type,Common::Localsocket_unsenddata[a].data);
    }
    Common::Localsocket_unsenddata.clear();
    Common::Localsocket_unsenddataLock.unlock();
}

void Handle::LocalSocket_SetUnfinshsenddata(QString id,QString type,QString data,emit_type emittype,QString sockettype)
{
    Common::Localsocket_unsenddataLock.lockForWrite();
    struct LocalSocket_UnSendData data1={id,type,data,emittype,sockettype};
    Common::Localsocket_unsenddata.append(data1);
    Common::Localsocket_unsenddataLock.unlock();
}


QString Handle::GetMD5(QByteArray data)
{
    QByteArray md5 = QCryptographicHash::hash(data, QCryptographicHash::Md5);
    return   QString(md5.toHex());
    // qDebug() << ba.toHex().constData();
}


QStringList Handle::GetDLLMd5()
{
    QStringList data;
    Common::Dll_Md5lock.lockForRead();

    QMap  <QString,QString>::const_iterator i;
    for (i = Common::Dll_Md5.constBegin(); i != Common::Dll_Md5.constEnd(); ++i) {    //对QMAP进行遍历
        QString dllname=i.key();
        QString md5=i.value();
        data.append(dllname+"$$"+md5);
    }

    Common::Dll_Md5lock.unlock();

    return  data;
}

QString Handle::CaculateNode_information()
{
    Common::tcp_server_SocketMapLock.lockForRead();
    QStringList alldata;
    QMap<tcp_socket*,QSharedPointer<M_Socket>>::const_iterator i;
    for (i = Common::tcp_server_SocketMap.constBegin(); i != Common::tcp_server_SocketMap.constEnd(); ++i) {    //对QMAP进行遍历
        i.value().data()->lock.lockForRead();
        if(i.value().data()->Socket_Type=="管理端")
        {
            i.value().data()->lock.unlock();
            continue;
        }
        QStringList data;
        data.append(i.value().data()->Socket_name);
        data.append( "cpu个数:"+i.value().data()->cpu_cout);
        data.append( "内存利用率:"+i.value().data()->Memory_usage);
        data.append( "内存大小:"+i.value().data()->Memory_size);
        data.append( "剩余内存:"+i.value().data()->Residual_memory);
        QStringList nodestatus;
        for(int a=0;a<i.value().data()->Caculate_status.size();a++)
        {
            if(i.value().data()->Caculate_status[a]==Cfree)
            {
                nodestatus.append("空闲");
            }else if(i.value().data()->Caculate_status[a]==Caculating)
            {
                nodestatus.append("繁忙");
            }else{
                nodestatus.append("未知");
            }
        }

        data.append( nodestatus.join("@"));

        alldata.append(data.join("#"));
        i.value().data()->lock.unlock();
    }
    Common::tcp_server_SocketMapLock.unlock();
    return alldata.join("$");
}

void Handle::ReadDll()
{
    Common::Dll_Md5lock.lockForWrite();
    Common::Dll_Md5.clear();
    Common::Dll_Md5lock.unlock();
    //不存在dll文件夹直接退出
    if(!isDirExist(QCoreApplication::applicationDirPath()+"\\"+"DLL"))
    {
        return;
    }
    QString file_path=QCoreApplication::applicationDirPath()+"\\"+"DLL";
    QDir dir(file_path);
    QStringList nameFilters;
    nameFilters << "*.dll";
    QStringList dllname = dir.entryList(nameFilters, QDir::Files|QDir::Readable, QDir::Name);
    QMap<QString,QString>  md5;
    for(int a=0;a<dllname.size();a++)
    {
        QString DllPath=QCoreApplication::applicationDirPath()+"\\"+"DLL"+"\\"+dllname[a];
        QFile file(DllPath);
        if(!file.open(QIODevice::ReadOnly))
        {
            qDebug()<<dllname[a]<<"读取失败!";
            continue;
        }
        QByteArray dllData= file.readAll();
        file.close();
        md5[dllname[a]]=GetMD5(dllData);
    }
    Common::Dll_Md5lock.lockForWrite();
    for(int a=0;a<dllname.size();a++)
    {
        Common::Dll_Md5[dllname[a]]=md5[dllname[a]];
    }
    Common::Dll_Md5lock.unlock();
}
